﻿using ChuanYe.IBLL;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using SJPlatForm.Web.Common;
using ChuanYe.Commom;
using System.Web.Http.Cors;
using ChuanYe.Utils;

namespace SJPlatForm.Web.Controllers
{
    [EnableCors("*", "*", "*")]
    public class FilesController : ApiController
    {
        [Dependency]
        public INewsBLL n_bll { get; set; }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public HttpResponseMessage Upload()
        {
            try
            {
                //安全验证，上线需要去掉注释
                //string blackbox = HttpContext.Current.Request.Params["blackbox"];
                //if (string.IsNullOrEmpty(blackbox))
                //{
                //    Log.Attack("缺少blackbox信息！");
                //    return this.Request.CreateResponse(HttpStatusCode.OK, "kill");
                //}

                //string TokenInfo = DESEncrypt.DecryptByAES(blackbox, Common.ConfigHelper.AES_KEY, Common.ConfigHelper.AES_IV);
                //if (string.IsNullOrEmpty(TokenInfo))
                //{
                //    Log.Attack("缺少Token");
                //    return this.Request.CreateResponse(HttpStatusCode.OK, "kill");
                //}
                //else
                //{
                //    string[] TokenInfoArr = TokenInfo.Split(',');
                //    int ID = Convert.ToInt32(TokenInfoArr[0]);
                //    UsersInfosDAL ub = new UsersInfosDAL();
                //    if (!ub.IsIDRight(ID))
                //    {
                //        Log.Attack("错误的Token：" + TokenInfoArr[0]);
                //        return this.Request.CreateResponse(HttpStatusCode.OK, "kill");
                //    }

                //    DateTime date = ValueConvert.TimeStampToDateTime(TokenInfoArr[1]);
                //    System.TimeSpan t3 = DateTime.Now - date;
                //    if (t3.TotalMinutes > Convert.ToInt32(TokenInfoArr[2]))
                //    {
                //        Log.Attack("时间戳超时，时差分钟数：" + t3.TotalMinutes);
                //        return this.Request.CreateResponse(HttpStatusCode.OK, "kill");
                //    }
                //}

                if (!Request.Content.IsMimeMultipartContent())
                {
                    this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
                }

                var UploadFolder = GetUploadFolder();
                HttpFileCollection files = HttpContext.Current.Request.Files;
                string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                List<UploadDataModel> UploadDataModelList = new List<UploadDataModel>();
                UploadDataModel model = new Controllers.UploadDataModel();
                List<string> exFile = new List<string>();
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    HttpPostedFile file = files[iFile];
                    string Time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string fileExtension = Path.GetExtension(file.FileName).ToLower();
                    string filePath = UploadFolder + "/" + Time+fileExtension;
                    bool exist=IsExistExtension(fileExtension);
                    if (!exist)//没有上传指定类型的扩展名
                    {
                        exFile.Add(fileExtension);
                        break;
                    }
                    file.SaveAs(BaseDirectory + filePath);
                    model.FileName = file.FileName;
                    model.FilePath = filePath;
                    model.FileSize = Convert.ToDecimal(file.ContentLength) / 1024 / 1024;
                    UploadDataModelList.Add(model);
                }

                if (exFile.Count > 0)
                {
                    return this.Request.CreateResponse(HttpStatusCode.OK, new { exFile });
                }
                else
                {
                    return this.Request.CreateResponse(HttpStatusCode.OK, new { UploadDataModelList });
                }
            }
            catch (Exception ex)
            {
                Log.Error("FilesController", ex.ToString());
                return this.Request.CreateResponse(HttpStatusCode.OK, "出现错误！");
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="obj">文件路径：fileUrl</param>
        /// <returns></returns>
        //[ApiSecurityFilter]
        [System.Web.Http.HttpPost]
        public void FileDelete(dynamic obj)
        {
            string fileUrl = obj.fileUrl;
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileUrl);
            File.Delete(filePath);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="obj">文件路径：fileUrl</param>
        /// <returns></returns>
        //[ApiSecurityFilter]
        [System.Web.Http.HttpPost]
        public IHttpActionResult GetFileFromWebApi(dynamic obj)
        {
            try
            {
                
                var browser = String.Empty;
                if (HttpContext.Current.Request.UserAgent != null)
                {
                    browser = HttpContext.Current.Request.UserAgent.ToUpper();
                }
                string fileUrl = obj.fileUrl;
                //fileUrl = fileUrl.Replace('/', '\\');
                //string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileUploads/2017年10月/2017年10月26日/20171026135913749上传测试文档.txt");
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileUrl);
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                FileStream fileStream = File.OpenRead(filePath);
                httpResponseMessage.Content = new StreamContent(fileStream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName =
                        browser.Contains("FIREFOX")
                            ? Path.GetFileName(filePath)
                            : HttpUtility.UrlEncode(Path.GetFileName(filePath))
                    //FileName = HttpUtility.UrlEncode(Path.GetFileName(filePath))
                };

                return ResponseMessage(httpResponseMessage);
            }
            catch (Exception ex)
            {
                Log.Error("FilesController", ex.ToString());
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                return ResponseMessage(httpResponseMessage);
            }
        }

        private string GetUploadFolder()
        {
            //文件的上传路径
            //var uploadFolder = "FileUploads/" + DateTime.Now.Year + "年" + DateTime.Now.Month + "月/" + DateTime.Now.ToLongDateString();
            var MonthDirectory = "FileUploads/" + DateTime.Now.ToString("yyyyMM");
            var uploadFolder= MonthDirectory + "/"+ DateTime.Now.ToString("yyyyMMdd");

            //获取根路径
            var root = HttpContext.Current.Server.MapPath(uploadFolder);
            var MonthDirectoryRoot = HttpContext.Current.Server.MapPath(MonthDirectory);

            //创建文件夹
            Directory.CreateDirectory(MonthDirectoryRoot);
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory+ uploadFolder);
            
            return uploadFolder;
        }

        //从Provider中获取表单数据
        private object GetFormData<T>(MultipartFormDataStreamProvider result)
        {
            if (result.FormData.HasKeys())
            {
                var unescapedFormData = Uri.UnescapeDataString(result.FormData.GetValues(0).FirstOrDefault() ?? String.Empty);

                if (!String.IsNullOrEmpty(unescapedFormData))
                {
                    return JsonConvert.DeserializeObject<T>(unescapedFormData);
                }
            }
            return null;
        }

        //获取反序列化文件名
        private string GetDeserializedFileName(MultipartFileData fileData)
        {
            var fileName = GetFileName(fileData);
            return JsonConvert.DeserializeObject(fileName).ToString();
        }


        private bool IsExistExtension(string fileExtension)
        {
            bool isExist = false;
            string[] allowExtension = { ".txt",".gif",".rtf", ".png", ".jepg", ".jpg", ".bmp", ".pdf", ".xls", ".doc", ".docx", ".rar", ".zip", ".xlsx", ".pptx", ".ppt" };
            var exist = allowExtension.Where(p => p == fileExtension).ToArray().FirstOrDefault();
            if (!string.IsNullOrEmpty(exist))
            {
                isExist = true;
            }
            return isExist;
        }

        //获取文件名
        public string GetFileName(MultipartFileData fileData)
        {
            return fileData.Headers.ContentDisposition.FileName;
        }

        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }

    public class UploadDataModel
    {
        /// <summary>
        /// 附件ID
        /// </summary>
        public int FileID { get; set; }
        /// <summary>
        /// 文件全路径
        /// </summary>
        public string FilePath { get; set; }
        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 文件大小
        /// </summary>
        public decimal FileSize { get; set; }
    }
}